package cn.edu.nuc.ssm.controller;

import cn.edu.nuc.ssm.entity.Admin;
import cn.edu.nuc.ssm.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2017/4/24.
 */
@Controller
@RequestMapping("/back")
public class BackLogin {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String index(){

        return "back/login";
    }
    @RequestMapping(value = "/welcome",method = RequestMethod.GET)
    public String welcome(){

        return "back/welcome";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session,Model model){

        Admin login = adminService.login(username, password);

        if (login==null){

            session.setAttribute("msg","用户名密码错误");
            return "redirect:/back/login";
        }
        session.setAttribute("admin",login);


        return "back/index";
    }

    @RequestMapping(value = "/modifyPwd",method = RequestMethod.GET)
    public String tomodifyPwd() {

        return "back/modifyPwd";
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public String modifyPwd(String password, String pwdpassword, HttpSession session, Model model){

        Admin admin = (Admin)session.getAttribute("admin");

        if (admin==null){

            return "redirect:/back/login";
        }

        Admin findAdmin = adminService.findById(admin.getId());

        if ( findAdmin.getPassword().equals(password)  ){

            adminService.updatePasswordByid(admin.getId(),pwdpassword);

            session.removeAttribute("admin");

            return "redirect:/back/login";
        }

        model.addAttribute("msg","原密码输入错误");


        return "back/modifyPwd";
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpSession session){

        session.removeAttribute("admin");

        return "redirect:/back/login";
    }

}
